package com.lijing.mock.manager;

import com.lijing.mock.model.bo.MockRegionBO;
import com.lijing.mock.model.dto.UrlMockDTO;
import com.lijing.mock.model.bo.UrlRandomBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


/**
 * 本地缓存管理器
 * @author by lijing
 * @date 2019/12/4 0004 9:39
 */
@Slf4j
@Component
public class LocalCacheManager {

    private final UrlMockManager urlMockManager;

    public LocalCacheManager(UrlMockManager urlMockManager) {
        this.urlMockManager = urlMockManager;
    }

    /**
     * url mock随机配置信息
     * @param urlId urlId
     * @return 随机配置信息
     */
    @Cacheable(value="users", key="#urlId")
    public UrlRandomBO getUrlRandom(String urlId){
        List<UrlMockDTO> urlMockList = urlMockManager.queryByUrlId(urlId);
        if(urlMockList==null||urlMockList.size()<1){
            return null;
        }
        return processUrlRandom(urlMockList);
    }


    /**
     * 从url配置信息中提取随机权重信息
     * @param urlMockList url配置信息
     * @return url权重随机信息
     */
    private UrlRandomBO processUrlRandom(List<UrlMockDTO> urlMockList){
        int weight = 0;
        List<MockRegionBO> regionList = new ArrayList<>(urlMockList.size());
        for (UrlMockDTO urlMock : urlMockList) {
            MockRegionBO mockRegion = new MockRegionBO(urlMock.getId(), weight, weight + urlMock.getWeight(),urlMock.getMockDataList());
            weight = mockRegion.getRightValue();
            regionList.add(mockRegion);
        }
        UrlRandomBO urlRandom = new UrlRandomBO();
        urlRandom.setTotalWeight(weight);
        urlRandom.setWeightRegion(regionList);
        return urlRandom;
    }
}
